package com.cch.platform.util;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Logger;

public class MapUtil {
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static void copyMap(Map to, Map from, boolean override) {
		if ((from == null) || (to == null)) {
			return;
		}
		Iterator iterator = from.keySet().iterator();
		while (iterator.hasNext()) {
			Object key = iterator.next();
			Object val = to.get(key);
			Object val2 = from.get(key);
			if ( override || val == null || StringUtil.isEmpty(val.toString()) ){
				to.put(key, val2);
			}
		}
	}

	@SuppressWarnings("unchecked")
	public static <K, V> Map<K, V> bean2Map(Object javaBean) {
		Map<K, V> ret = new HashMap<K, V>();
		try {
			Method[] methods = javaBean.getClass().getDeclaredMethods();
			for (Method method : methods) {
				if (method.getName().startsWith("get")) {
					String field = method.getName();
					field = field.substring(field.indexOf("get") + 3);
					field = field.toLowerCase().charAt(0) + field.substring(1);
					Object value = method.invoke(javaBean, (Object[]) null);
					ret.put((K) field, (V) (null == value ? "" : value));
				}
			}
		} catch (Exception e) {
		}
		return ret;
	}
	

	protected static Log logger = LogFactory.getLog(MapUtil.class); // 日志
	/**
	 * 转换时对map中的key里的字符串会做忽略处理的正则串
	 */
	private static final String OMIT_REG = "_";

	/**
	 * 将map集合转换成Bean集合，Bean的属性名与map的key值对应时不区分大小写，并对map中key做忽略OMIT_REG正则处理
	 * 
	 * @param <E>
	 * @param cla
	 * @param mapList
	 * @return
	 */
	public static <E> List<E> toBeanList(Class<E> cla,
			List<Map<String, Object>> mapList) {

		List<E> list = new ArrayList<E>(mapList.size());

		for (Map<String, Object> map : mapList) {
			E obj = toBean(cla, map);
			list.add(obj);
		}

		return list;
	}
	

	/**
	 * 将map转换成Bean，Bean的属性名与map的key值对应时不区分大小写，并对map中key做忽略OMIT_REG正则处理
	 * 
	 * @param <E>
	 * @param cla
	 * @param map
	 * @return
	 */
	@SuppressWarnings({ "rawtypes" })
	public static <E> E toBean(Class<E> cla, Map<?,?> map) {

		// 创建对象
		E obj = null;
		try {
			obj = cla.newInstance();
			if (obj == null) throw new Exception();
		} catch (Exception e) {
			logger.error("类型实例化对象失败,类型:" + cla);
			return null;
		}

		// 进行值装入
		Method[] ms = cla.getMethods();
		for (Method method : ms) {
			String field=methodToField(method.getName());
			Object v = map.get(field);	
			Class[] clas = method.getParameterTypes();
			if (v != null && clas.length == 1) {
				try {
					method.invoke(obj, v);
				} catch (Exception e) {
					logger.error("属性值装入失败,装入方法：" + cla + "."
							+ method.getName() + ".可装入类型" + clas[0]
							+ ";欲装入值的类型:" + v.getClass());
				}
			}
		}

		return obj;
	}
	
	private static String methodToField(String method){
		String field=null;
		if(method.startsWith("get")||method.startsWith("set")){
			field=method.substring(3);
			field = field.toLowerCase().charAt(0) + field.substring(1);
		}
		return field;
	}
}


